﻿/// <reference path="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\MicrosoftAjax.js" />
/// <reference path="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\SP.debug.js" />
ExecuteOrDelayUntilScriptLoaded(initialize, "sp.js");

var context = null;
var web = null;
var site = null;

var $TileThatIsBeingDragged = null;
var $ItemThatIsBeingDragged = null;
var clickedItem;
var actualQuery;

var libvalue;
var techlibvalue;
var sourcelibvalue;
var listid;
var forcecheckout;

var itemToPaste;
var clipBoardAction;

var warningNot;
var errorNot;
var $columns;

var doctypes = { "doc": "word.png", "docx": "word.png", "xls": "excel.png", "xlsx": "excel.png", "ppt": "ppoint.png", "pptx": "ppoint.png", "unknown": "unknown.png" };
var additionalDoctypes = "";

function getClickedItem() {
    return clickedItem;
}

//Onload
function initialize() {

    $.ajaxSetup({
        // Disable caching of AJAX responses
        cache: false
    });

    context = new SP.ClientContext.get_current();
    web = context.get_web();
    site = context.get_site();

    additionalDoctypes = $('#doctypes').val();
    $columns = $('#columns').val();

    SetDoctypes();

    actualQuery = '';
    BuildQuery(actualQuery);

}

function SetDoctypes() {
    var keyValues = additionalDoctypes.split(",");
    for (i = 0; i < keyValues.length; i++) {
        var pair = keyValues[i].split(":");
        doctypes[pair[0]] = pair[1];
    }
}

function BuildQuery(view) {
    $('#sharepoint_explorer_main').empty();

    if (!(actualQuery == '')) {
        var list = web.get_lists().getByTitle(libvalue);

        var query = new SP.CamlQuery();
        query.set_viewXml('');
        query.set_folderServerRelativeUrl(view);

        allItems = list.getItems(query);

        context.load(allItems, 'Include(File, FileSystemObjectType, ID, FileLeafRef)');
    }
    else {
        allItems = web.get_lists();
        context.load(allItems, 'Include(Title, BaseType, Hidden)');
    }

    context.load(web);
    context.load(site);
    
    context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}

function success() {
    $('#sharepoint_explorer_main').append(BuildTable());

    $('.tile').draggable({ containment: '#sharepoint_explorer_main', start: function () {
        $TileThatIsBeingDragged = $(this);
        SingleClick($(this));
    } 
    });
    $('.tile').droppable({ drop: function (event, ui) {
        DroppedTile($(this).attr('id'));
    }});
    $('.tile').dblclick(function () {
        DoubleClicked($(this).attr('id'));
    });
    $('.tile').click(function () {
        SingleClick(this);
    });
}

function failed(sender, args) {
    alert('failed. Message:' + args.get_message());
}

function DoubleClicked(itemid) {
    var urlcreation = GetPath();
    if (itemid.match(/^lib_/)) {
        libvalue = itemid.replace('lib_', '');
        
        $.getJSON(urlcreation + '/_vti_bin/SharePoint.Desktop.Service/desktopservice.svc/GetTechnicalLibraryName?LibraryName=' + libvalue, function (response) {
            actualQuery = response.TechnicalName;
            techlibvalue = response.TechnicalName;
            forcecheckout = response.ForceCheckOut;
            listid = response.ListId;
            BuildQuery(actualQuery);
            clickedItem = null;
            RefreshCommandUI();
        });
    }
    else {
        var list = web.get_lists().getByTitle(libvalue);
       
        $.getJSON(urlcreation + '/_vti_bin/SharePoint.Desktop.Service/desktopservice.svc/GetItemUrl?Item=' + itemid + '&Library=' + libvalue, function (response) {
            if (response.IsFolder == true) {
                actualQuery = response.UrlValue;
                BuildQuery(actualQuery);
                clickedItem = null;
                RefreshCommandUI();
            }
            if (response.IsFolder == false) {
                OpenDocument(response.UrlValue);
            }
        });
    }
}

function SingleClick(item) {
    if (clickedItem != null) {
        $(clickedItem).removeClass("selectedtile");
    }
    $(item).addClass("selectedtile");
    clickedItem = item;
    RefreshCommandUI();
}

function BrowseUp() {
    actualQuery = actualQuery.substring(0, actualQuery.lastIndexOf("/"));

    BuildQuery(actualQuery);
    clickedItem = null;
    RefreshCommandUI();
}

function Desktop() {
    actualQuery = '';

    BuildQuery(actualQuery);
    clickedItem = null;
    RefreshCommandUI();
}

function CopyCut(action) {
    itemToPaste = $(clickedItem).attr('id');
    sourcelibvalue = libvalue;
    clipBoardAction = action;
    RefreshCommandUI();
}

function CheckIn() {
    var path = GetPath();
    path = path + '/' + actualQuery + '/' + $(clickedItem).find('.filename').html();
    OpenCheckInDialog(listid, path);
}

function CheckOut() {
    var path = GetPath();
    path = path + '/' + actualQuery + '/' + $(clickedItem).find('.filename').html();

    var item = web.getFileByServerRelativeUrl(path);
    item.checkOut();
    context.executeQueryAsync(Function.createDelegate(this, checkIn_Success), Function.createDelegate(this, checkIn_Fail));
}

function checkIn_Success(sender, args) {
    BuildQuery(actualQuery);
    clickedItem = null;
    RefreshCommandUI();
}
function checkIn_Fail(sender, args) {
    alert('There was an error checking the item in.');
}

function NewItem() {
    var path = GetPath();
    path = path + '/' + actualQuery;
    OpenNewDialog(listid, path);
}

function NewFolder() {
    var path = GetPath();
    path = path + '/' + actualQuery;
    OpenNewFolderDialog(path);
}

function GetPath() {
    var path = '';
    if (web.get_serverRelativeUrl() != '/') {
        path = path + web.get_serverRelativeUrl();
    }
    return path;
}

function Delete() {
    var answer = confirm("Are you sure you want to delete the item?")
    if (answer) {
        var path = web.get_serverRelativeUrl() + actualQuery + '/' + $(clickedItem).find('.filename').html();
        var item = web.getFileByServerRelativeUrl(path);
        item.deleteObject();
        context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
    }
}

function onQuerySucceeded() {
    BuildQuery(actualQuery);
    clickedItem = null;
    RefreshCommandUI();
}

function onQueryFailed(sender, args) {
    alert('There was an error deleting the item.');
}

function Edit() {
    OpenEditDialog($(clickedItem).attr('id'));
}

function Paste() {
    warningNot = SP.UI.Notify.addNotification('Pasting. Please wait...', true);
    var urlcreation = GetPath();
    $.getJSON(urlcreation + '/_vti_bin/SharePoint.Desktop.Service/desktopservice.svc/MoveItemByUrl?DraggedItem=' + itemToPaste + '&DroppedItemUrl=' + actualQuery + '&Library=' + sourcelibvalue + '&Action=' + clipBoardAction, function (response) {
        if (response == true) {
            BuildQuery(actualQuery);
            if (clipBoardAction == 'cut') {
                itemToPaste = null;
            }
            RefreshCommandUI();
            SP.UI.Notify.removeNotification(warningNot);
        }
        if (response == false) {
            itemToPaste = null;
            RefreshCommandUI();
            SP.UI.Notify.removeNotification(warningNot);
            SP.UI.Notify.addNotification('<span style=\'color:red\'>There was an error pasting.</span>', false);
        }
    });
}

function OpenDocument(url) {
    var dispExArgs = '';
    dispExArgs += "this,";
    dispExArgs += "event,";
    dispExArgs += "'TRUE',";
    dispExArgs += "'FALSE',";
    dispExArgs += "'SharePoint.OpenDocuments.3',";
    dispExArgs += "'1',";
    dispExArgs += "'SharePoint.OpenDocuments',";
    dispExArgs += "'',";
    dispExArgs += "'',";
    dispExArgs += "'',";
    dispExArgs += "'1',";
    dispExArgs += "'0',";
    dispExArgs += "'0',";
    dispExArgs += "'0x7fffffffffffffff',";
    dispExArgs += "'',";
    dispExArgs += "''";

    var urlcreation = GetPath();

    var linkHtml = '<a onclick="return DispEx(' + dispExArgs + ');" href="' + urlcreation + '/' + url + '">' + urlcreation + '/' + url + '</a>';
    var link = $(linkHtml);

    $('body').append(link);
    link.get(0).click();
    link.remove();
}


function BuildTable() {

    var ListEnumerator = this.allItems.getEnumerator();
    
    $count = 1;

    $table = "<table><tr>";
  
    while (ListEnumerator.moveNext()) {
        var currentItem = ListEnumerator.get_current();

        if (!(currentItem instanceof SP.ListItem)) {
            if (currentItem.get_baseType() == 0 || currentItem.get_hidden() == true) {
                continue;
            }
        }

        if ($count - 1 != 0 && $count - 1 % $columns == 0) {
            $table = $table + "<tr>";
        }
     
        $table = $table + "<td>";
        $table = $table + BuildImage(currentItem);
        $table = $table + "</td>";

        if ($count % $columns == 0) {
            $table = $table + "</tr>";
        }

        $count++;
    }

    if ($count % $columns != 0) {
        $table = $table + "</tr>";
    }

    $table = $table + "</table>";

    return $table;
}

function BuildImage(item) {
    var id, imageUrl, name, checkedout, objecttype;
    
    if (item instanceof SP.ListItem) {
        id = item.get_item('ID');
        name = item.get_item('FileLeafRef');
        checkedout = 2;

        imageUrl = '';

        var ff = item.get_fileSystemObjectType();

        if (ff == '1') {
            imageUrl = '_layouts/images/SharePoint.Desktop/folder.png';
            objecttype = 1;
        }
        if (ff == '0') {
            
            var file = item.get_file();
            checkedout = file.get_checkOutType();
            objecttype = 0;

            var extension = GetFileExtension(name);
            var image = doctypes[extension];
            if (image != undefined) {
                imageUrl = '_layouts/images/SharePoint.Desktop/' + image;
            }
            else {
                imageUrl = '_layouts/images/SharePoint.Desktop/' + doctypes['unknown'];
            }
        }
    }
    else {
        id = 'lib_' + item.get_title();
        imageUrl = '_layouts/images/SharePoint.Desktop/libraryIcon.png';
        name = item.get_title();
        checkedout = 2;
        objecttype = 3;
    }

    return Tile(id, imageUrl, name, checkedout, objecttype);
}

function GetFileExtension(filename) {
    var extensionpoint = filename.lastIndexOf('.');
    if (extensionpoint > -1) {
        return filename.substring(extensionpoint + 1);
    }
    return "";
}

function Tile(id, imageUrl, name, checkedout, objecttype) {

    $tile = '<table id="' + id + '" class="tile" cellpadding="0" cellspacing="0" border="0"><tr><td width="75" height="60" align="center" valign="middle">';

    $tile = $tile + "<img class='innertile' src='" + imageUrl + "' alt='Folder' height='50' width='50' />";

    if (checkedout == 0) {
        $tile = $tile + "<img class='arrow' src='_layouts/images/SharePoint.Desktop/checkedOut.png' alt='Folder' height='30' width='30' />";
    }

    $tile = $tile + "</td></tr><tr><td width='75' height='50' valign='middle'><p>" + name + "</p></td></tr>";

    $tile = $tile + "<tr style='visibility:hidden;display:none'><td><div class='checkedout'>" + checkedout + "</div></td></tr>";

    $tile = $tile + "<tr style='visibility:hidden;display:none'><td><div class='objecttype'>" + objecttype + "</div></td></tr>";

    $tile = $tile + "<tr style='visibility:hidden;display:none'><td><div class='filename'>" + name + "</div></td></tr>";
    
    $tile = $tile + "</table>";

    return $tile;
}

function DroppedTile($DroppedTileID) {
    if (actualQuery == '' || $('#' + $DroppedTileID).find('.objecttype').html() != 1 || $($TileThatIsBeingDragged).find('.checkedout').html() == 0) {
        return;
    }

    warningNot = SP.UI.Notify.addNotification('Moving. Please wait...', true);
    $($TileThatIsBeingDragged).hide();
    var urlcreation = GetPath();
    $.getJSON(urlcreation + '/_vti_bin/SharePoint.Desktop.Service/desktopservice.svc/MoveItemByID?DraggedItem=' + $($TileThatIsBeingDragged).attr('id') + '&DroppedItem=' + $DroppedTileID + '&Library=' + libvalue + '&Action=cut', function (response) {
        if (response == true) {
            $($TileThatIsBeingDragged).remove();
            RefreshCommandUI();
            SP.UI.Notify.removeNotification(warningNot);
        }
        if (response == false) {
            $($TileThatIsBeingDragged).show();
            RefreshCommandUI();
            SP.UI.Notify.removeNotification(warningNot);
            SP.UI.Notify.addNotification('<span style=\'color:red\'>There was an error moving.</span>', false);
        }
    });
}

function DialogCallback(dialogResult, returnValue) {
    BuildQuery(actualQuery);
    clickedItem = null;
    RefreshCommandUI();
}

function OpenEditDialog(id) {

    var urlcreation = GetPath();

    var options = {
        url: urlcreation + '/' + techlibvalue + '/Forms/EditForm.aspx?ID=' + id,
        width: 700,
        height: 400,
        dialogReturnValueCallback: DialogCallback
    };

    SP.UI.ModalDialog.showModalDialog(options);
}

function OpenNewFolderDialog(rootfolder) {

    var urlcreation = GetPath();
    urlcreation = urlcreation + '/' + techlibvalue;

    var options = {
        url: urlcreation + '/Forms/Upload.aspx?RootFolder=' + rootfolder + '&Type=1',
        width: 700,
        height: 400,
        dialogReturnValueCallback: DialogCallback
    };

    SP.UI.ModalDialog.showModalDialog(options);
}

function OpenNewDialog(listid, location) {

    var urlcreation = GetPath();

    var options = {
        url: urlcreation + '/_layouts/Upload.aspx?List=' + listid + '&RootFolder=' + location,
        width: 700,
        height: 400,
        dialogReturnValueCallback: DialogCallback
    };

    SP.UI.ModalDialog.showModalDialog(options);
}

function OpenCheckInDialog(listid, filename) {

    var urlcreation = GetPath();

    var options = {
        url: urlcreation + '/_layouts/checkin.aspx?List={' + listid + '}&FileName=' + filename + '&IsDlg=1',
        width: 700,
        height: 400,
        dialogReturnValueCallback: DialogCallback
    };

    SP.UI.ModalDialog.showModalDialog(options);
}